﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AddIn.EA.Core;
using AddIn.EA.Core.Interface;

namespace AddIn.EA.Core.Management
{
    internal class AddInItem : List<IAddInItem>, IAddInItem
    {
        public AddInItem() { }

        public AddInItem(string itemName) : this(itemName, null)
        { 
        }

        public AddInItem(string itemName, IAddInArchitecture addIn) 
        {
            this.ItemName = itemName;
            this.AddIn = addIn;
        }

        public IAddInItem Parent { get; set; }
        public string ItemName { get; set; }
        public IAddInArchitecture AddIn { get; set; }
        
        public string BaseMenuItem
        {
            get { return this.IsMenu ? string.Concat("-", this.ItemName) : this.ItemName; }
        }
        
        public string MenuName
        {
            get { return this.Parent == null ? string.Empty : this.Parent.ItemName; }
        }
        
        public bool IsMenu
        {
            get { return (this.Count > 0); }
        }

        public bool HasAddIn
        {
            get { return (this.AddIn != null); }
        }

        public IAddInItem FindItem(string itemName)
        {
            if (itemName == this.ItemName || itemName == this.BaseMenuItem)
                return this;

            if (this.Contains(itemName))
                return this[this.IndexOf(itemName)];
            else
                return FindItemInChilds(itemName);
        }

        public bool Contains(string itemName)
        {
            return (this.IndexOf(itemName) >= 0);
        }

        public int IndexOf(string itemName)
        {
            foreach (AddInItem item in this)
            {
                if (item.BaseMenuItem == itemName || item.ItemName == itemName)
                    return this.IndexOf(item);
            }

            return -1;
        }

        public void Add(AddInItem item)
        { 
            if(!this.Contains(item.ItemName))
                base.Add(item);
        }

        public string[] ToArray()
        {
            return (from addIn in this
                    select addIn.BaseMenuItem).ToArray<string>();
        }

        private IAddInItem FindItemInChilds(string itemName)
        {
            foreach (IAddInItem item in this)
            {
                IAddInItem itemFound = item.FindItem(itemName);
                if (itemFound != null)
                    return itemFound;
            }

            return null;
        }
    }
}
